import {BASE_URL, TIMEOUT} from './config';
import commondUtil from '../utils/commondUtil';
import Log from '../utils/log';

/**
 * 请求封装
 * @param params
 * @returns {Promise}
 */
export function httpRequest(params) {
  let url = params.url;
  let method = params.method;
  let header = params.header ? params.header : {};
  if (!url.startsWith("/auth")) {
    header['token'] = wx.getStorageSync('token');
  }

  wx.showLoading({
    title: "加载中",
    mask: true //开启蒙版遮罩
  });

  return new Promise((resolve, reject) => {
    wx.request({
      url: BASE_URL + url,
      timeout: TIMEOUT,
      method: method,
      data: params.params,
      header: {
        'Content-Type': 'application/json',
        ...header
      },
      success: (res) => {
        closeLoading();
        if (res.data?.code == 401) {
          // token过期，请求续期
          handleTokenExprie(params, resolve);
          return;
        }

        resolve(res.data);
      },
      fail: (res) => {
        closeLoading();
        wx.showToast({
          title: res.data.message ? res.data.message : '请求数据失败，请稍后重试',
          icon: 'none',
          duration: 3000
        })
        reject(res);
      },
    });
  });
}

function handleTokenExprie(oldParams, resolve) {
  const refreshToken = wx.getStorageSync('refreshToken');
  if (commondUtil.isBlank(refreshToken)) {
    resolve({});
    jumpToLoginPage();
    return;
  }

  wx.showLoading({
    title: "加载中",
    mask: true //开启蒙版遮罩
  });
  wx.request({
    url: BASE_URL + "/auth/tokenRenewal",
    timeout: TIMEOUT,
    method: 'get',
    data: {
      refreshToken
    },
    header: {
      'Content-Type': 'application/json',
    },
    success: (res) => {
      closeLoading();
      if (commondUtil.isBlank(res.data?.data?.token)) {
        resolve({});
        jumpToLoginPage();
        return;
      }

      wx.setStorageSync('token', res.data.data.token);
      // 重新发起旧请求
      httpRequest(oldParams).then(resp => {
        resolve(resp);
      }).catch(() => {
        resolve({});
      });
    },
    fail: (res) => {
      closeLoading();
      Log.errorAll("token续期失败", res);
      resolve({});
      jumpToLoginPage();
    },
  });
}
/**
 * 跳转到登录页
 */
function jumpToLoginPage() {
  wx.showToast({
    title: "登录超时，请重新登录",
    icon: 'none'
  });

  wx.removeStorageSync('token');
  wx.removeStorageSync('refreshToken');
  wx.removeStorageSync('userInfo');
  if (getCurPageUrl() == 'pages/login/login') {
    return;
  }

  wx.redirectTo({
    url: '/pages/login/login',
    fail: e => {
      Log.warnAll("登陆超时，跳转到登录页失败！", e)
    },
  });
}


function getCurPageUrl() {
  const pages = getCurrentPages();
  if (pages == null || pages.length < 1) {
    return null;
  }
  return pages[pages.length > 1 ? (pages.length - 2) : 0].route
}

function closeLoading() {
  wx.hideLoading({
    noConflict: true,
    fail: (e) => {
      Log.errorAll("关闭加载弹窗异常", e);
    },
  })
}